<template>
  <div class="login-container">

    <el-form ref="phoneForm"  class="login-form" autocomplete="on" label-position="left" v-show="phoneFlag" :rules="phoneRules" :model="phoneLoginData">
      <el-form-item prop="phone">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input ref="phone" v-model="phoneLoginData.phone" maxlength="11" placeholder="手机号" name="phone" type="text" tabindex="1" autocomplete="on" />
      </el-form-item>
      <el-form-item prop="phoneCode" >
        <!-- <div class="verify-wrapper">
          <el-input ref="phoneCode" v-model="phoneLoginData.phoneCode"  placeholder="验证码" name="phoneCode" type="text" tabindex="1" autocomplete="on" />
          <el-button :disabled="disabled" @click="getCode">{{valiBtn}}</el-button>
        </div> -->

        <el-col :span="15">
          <el-input ref="phoneCode" v-model="phoneLoginData.phoneCode"  placeholder="验证码" name="phoneCode" type="text" tabindex="1" autocomplete="on" style="width: 100%;"/>

        </el-col>
         <el-col :span="8">
                    <el-button :disabled="disabled" @click="getCode" style="width: 100%;line-height:20px">{{valiBtn}}</el-button>

        </el-col>

      </el-form-item>
       <el-button :loading="phoneLoading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handlePhoneLogin">登录</el-button>
      <el-button  type="primary" style="width:100%;margin-bottom:30px;margin-left:0px" @click.native.prevent="handleBackLogin">返回登录</el-button>
    </el-form>

  </div>
</template>

<script>
import {setToken} from '@/common/utils/auth'
import util from '@/common/utils/util.js'
import {login,auth,getUserInfo,callBack,sms,verify} from '@/api/login'

export default {
  name: "login",
  data() {
     var checkPhone = (rule, value, callback) => {
      const reg = /^0?(13[0-9]|15[012356789]|18[0-9]|14[578]|16[6]|17[035768]|19[19])[0-9]{8}$/
        if ( reg.test(this.phoneLoginData.phone) ) {
              return callback();
        }
        callback('请输入合法的手机号');
      };
    return {
      phoneFlag:true,
      loginErrMsg:"",
      loginData: {
        username: '',
        password: ''
      },
      loginRules: {
        username: [{ required: true, message:"请输入用户名", trigger: 'blur'}],
        password: [{ required: true, min:6, message:"密码不能少于6个字符", trigger: 'blur'}]
      },
      phoneRules: {
        phone: [{validator: checkPhone, required: true, trigger: 'blur' } ],
        phoneCode:[{required: true, message: '请输入验证码', trigger: 'blur' } ]
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      phoneLoginData: {
        phone: '',
        phoneCode: ''
      },
      phoneLoading:false,
      dialogVisible: false,     // 对话框显示和隐藏
      valiBtn:'获取验证码',
      disabled:false,
      userInfo:{
        
      }
    }
  },
  computed: {
    getRedirectUrl() {
      return encodeURIComponent(this.redirectUrl);
    },
    getAuthUrl() {
      return `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${this.appid}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${this.getRedirectUrl}`;
      //return `https:/login.dingtalk.com/oauth2/auth?redirect_uri=${this.getRedirectUrl}&response_type=code&client_id=${this.appid}&scope=openid&state=STATE&prompt=consent&`;
    },
    getGoto() {
      return encodeURIComponent(this.getAuthUrl);
    },
    getDingCodeConfig() {
      return { ...this.dingCodeConfig, goto: this.getGoto };
    },
  },
  created() {
    
  },
  mounted() {
    console.log("mounted方法")
    if(util.isLogin()){
      this.$router.replace("/index");
    }else{
      if (this.$route.query.code) {

            //loading.close();
        let code = this.$route.query.code
        let state = this.$route.query.state
        if(state == 'wxLogin'){
          console.log("微信扫码登录成功后请求后返回的code：" + code)
          this.getUserInfo(code,state)
        }else{
          
        }

      }
    }
  },
  methods: {
    //获取验证码
    //获取验证码 并只验证手机号 是否正确
    getCode(){
        this.$refs['phoneForm'].validateField('phone', (err) =>{
            if(err){
                console.log('未通过')
                return;
            }else{
                console.log('已通过')
                this.tackBtn();   //验证码倒数60秒
                sms({phoneNumber:this.phoneLoginData.phone}).then(res => {
                  if(res.code == 0) {
                    this.$message({showClose: true,message: res.msg,type: 'warning'})
                  }else if(res.code == 1) {
                    this.$message({showClose: true,message: '发送成功',type: 'success'})
                  }
                }).catch(res => {

                })

                }
            })
    },
    tackBtn(){       //验证码倒数60秒
          let time = 60;
          let timer = setInterval(() => {
              if(time == 0){
                  clearInterval(timer);
                  this.valiBtn = '获取验证码';
                  this.disabled = false;
              }else{
                  this.disabled = true;
                  this.valiBtn = time + '秒后重试';
                  time--;
              }
          }, 1000);
    },
    handlePhoneLogin() {  //点击登录 验证手机& 验证码是否符合条件
        this.$refs['phoneForm'].validate((valid) => {    // 为表单绑定验证功能
            if (valid) {
                let data = {
                    phoneNumber:this.phoneLoginData.phone,
                    code:this.phoneLoginData.phoneCode,
                    openId:this.userInfo.token.openId
                }
                verify(data).then(res => {
                  if(res.code == 0) {
                    this.$message({showClose: true,message: res.msg,type: 'warning'})
                  }else if(res.code == 1) {
                    this.successLogin(res.data)
                  }
                }).catch(res => {

                })
              } else {
                this.dialogVisible = true;
                return false;
            }
        });
    },
    successLogin(data){
       this.$message({showClose: true,message: '登录成功',type: 'success'})
      setToken(data.token);
      util.setCookie("uname", data.uname)
      util.setCookie("cname", data.cname)
      util.setCookie("rname", data.rname)
      this.$router.replace("/index")
    },
    getUserInfo(code,state){
      let loading = this.$loading({
            lock: true,
            text: '正在校验，请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
        getUserInfo({code:code,state:state}).then(res => {
            if(res.code == 0) {
              this.loginErrMsg = res.msg;
            }else if(res.code == 1) {
              //第二次授权登录
              if(res.data.uname){
                  this.successLogin(res.data)
              }else{
                //微信授权登录成功后，显示填写手机号界面
                this.userInfo = res.data
                this.phoneFlag = true
                this.loginFlag = false
                this.dingLoginFlag = false
                this.wxLoginFlag = false
              }
            }
            this.loading = false;
            loading.close();
          }).catch(res => {
            this.loading = false;
            loading.close();
          })
    },
    handleBackLogin() {
      this.$router.replace("/login");
    }
  }

}
</script>

<style lang="scss" >
$bg:#283443;
$light_gray:#fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg:#2d3a4b;
$dark_gray:#889aa4;
$light_gray:#eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 450px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container{
    padding: 6px 0px 6px 15px;
    color: $dark_gray;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

}
</style>
